{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b86781e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "usage: ipykernel_launcher.py [-h] [-t TIMES] [-s SIZE]\n",
      "ipykernel_launcher.py: error: unrecognized arguments: -f C:\\Users\\FANG\\AppData\\Roaming\\jupyter\\runtime\\kernel-8b03fedb-60df-42d2-a8f0-a3dd6380c265.json\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "2",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[1;31mSystemExit\u001b[0m\u001b[1;31m:\u001b[0m 2\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "import random\n",
    "import numpy as np\n",
    "import argparse\n",
    "\n",
    "class PSO:\n",
    "        #对象内置构造方法，初始化时自定义\n",
    "    def __init__(self, dimension, time, size, low, up, v_low, v_high):\n",
    "        # 初始化\n",
    "        self.dimension = dimension  # 变量个数  粒子\n",
    "        self.time = time  # 迭代的代数\n",
    "        self.size = size  # 种群大小    \n",
    "        self.bound = []  # 变量的约束范围   \n",
    "        self.bound.append(low)\n",
    "        self.bound.append(up)\n",
    "        self.v_low = v_low      #速度\n",
    "        self.v_high = v_high\n",
    "        #np.zeros创建一个用于存放粒子最优解以及群体最优解的数组\n",
    "        self.x = np.zeros((self.size, self.dimension))  # 所有粒子的位置\n",
    "        self.v = np.zeros((self.size, self.dimension))  # 所有粒子的速度\n",
    "        #pbest 个体最佳位置 gbest群体最佳位置\n",
    "        self.p_best = np.zeros((self.size, self.dimension))  # 每个粒子最优的位置\n",
    "        self.g_best = np.zeros((1, self.dimension))[0]  # 全局最优的位置\n",
    "\n",
    "        # 初始化第0代初始全局最优解\n",
    "        temp = float('inf')\n",
    "        for i in range(self.size):\n",
    "            for j in range(self.dimension):\n",
    "                self.x[i][j] = random.uniform(self.bound[0][j], self.bound[1][j])\n",
    "                self.v[i][j] = random.uniform(self.v_low, self.v_high)\n",
    "            self.p_best[i] = self.x[i]  \n",
    "            # 储存最优的个体\n",
    "            fit = self.fitness(self.p_best[i])\n",
    "            # 做出修改\n",
    "            if abs(fit) > temp:\n",
    "                self.g_best = self.p_best[i]\n",
    "                temp = fit\n",
    "\n",
    "    def fitness(self, x):\n",
    "        \"\"\"\n",
    "        函数计算\n",
    "        \"\"\"\n",
    "        #函数计算的公式\n",
    "        #这个不影响答案结果 影响结果的因素为粒子群算法的初始定义的几个值\n",
    "        x0 = x[0]\n",
    "        y = math.cos(x0) - x0\n",
    "        return y\n",
    "\n",
    "    def update(self, size): #更新粒子速度和位置\n",
    "        c1 = 2.0  # 粒子个体学习因子\n",
    "        c2 = 2.0  #粒子的社会学习因子\n",
    "        w = 0.9  # 自身权重因子 （速度惯性权重）\n",
    "        for i in range(size):\n",
    "            # 更新速度(核心公式)\n",
    "            # 即为这只鸟第i步的速度为=上一步自身的速度惯性+自我认知部分+社会认知部分\n",
    "            #v_{i}^{d}=wv_{i}^{d-1}+c_1r_1(pbest_{i}^{d}-x_{i}^{d})+c_2r_2(gbest^d-x_{i}^{d})\\\\\n",
    "            self.v[i] = w * self.v[i] + c1 * random.uniform(0, 3.14) * (\n",
    "                    self.p_best[i] - self.x[i]) + c2 * random.uniform(0, 3.14) * (self.g_best - self.x[i])\n",
    "            # 速度限制\n",
    "            for j in range(self.dimension):\n",
    "                #取速度值               \n",
    "                if self.v[i][j] < self.v_low:\n",
    "                    self.v[i][j] = self.v_low\n",
    "                if self.v[i][j] > self.v_high:\n",
    "                    self.v[i][j] = self.v_high\n",
    "            # 更新位置\n",
    "            self.x[i] = self.x[i] + self.v[i]\n",
    "            # 位置限制\n",
    "            for j in range(self.dimension):\n",
    "                if self.x[i][j] < self.bound[0][j]:\n",
    "                    self.x[i][j] = self.bound[0][j]\n",
    "                if self.x[i][j] > self.bound[1][j]:\n",
    "                    self.x[i][j] = self.bound[1][j]\n",
    "            # 更新p_best和g_best\n",
    "            if abs(self.fitness(self.x[i])) < abs(self.fitness(self.p_best[i])):\n",
    "                self.p_best[i] = self.x[i]\n",
    "            if abs(self.fitness(self.x[i])) < abs(self.fitness(self.g_best)):\n",
    "                self.g_best = self.x[i]\n",
    "\n",
    "    def pso(self):\n",
    "        self.final_best = np.array([random.uniform(0, 3.14)])\n",
    "        for _ in range(self.time):\n",
    "            self.update(self.size)\n",
    "            if abs(self.fitness(self.g_best)) < abs(self.fitness(self.final_best)):\n",
    "                self.final_best = self.g_best.copy()\n",
    "            temp = self.fitness(self.final_best)\n",
    "        print('当前最佳位置(x)：', self.final_best[0])\n",
    "        print('当前的最佳适应度(y)：', temp)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    parser = argparse.ArgumentParser()\n",
    "    parser.add_argument('-t', dest='times')\n",
    "    parser.add_argument('-s', dest='size')\n",
    "    args = parser.parse_args()\n",
    "\n",
    "    time = 1\n",
    "    size = 50\n",
    "    dimension = 1\n",
    "    v_low = -0.001\n",
    "    v_high = 0.005\n",
    "    low = [0.01]\n",
    "    up = [3.14]\n",
    "    pso = PSO(dimension, time, size, low, up, v_low, v_high)\n",
    "    pso.pso()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dda8238b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
